package com.bigseller.study;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class GoogleBarCodeUtils {

    /**
     * 条形码宽度
     */
    private static final int WIDTH = 300;

    /**
     * 条形码高度
     */
    private static final int HEIGHT = 52;

    /**
     * 加文字 条形码
     */
    private static final int WORD_HEIGHT = 110;

    /**
     * 条形码右下角第一段数据
     */
    private static final String RIGHT_FIRST_WORDS = "superMan";

    private static final String RIGHT_SECOND_WORDS = "Made in China";

    /**
     * 设置 条形码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            // 设置编码方式
            put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 容错级别 这里选择最高H级别
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            put(EncodeHintType.MARGIN, 1);
        }
    };

    /**
     * 生成 图片缓冲
     *
     * @param vaNumber VA 码
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage getBarCode(String vaNumber) {
        try {
            Code128Writer writer = new Code128Writer();
            // 编码内容, 编码类型, 宽度, 高度, 设置参数
            BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
       // BufferedImage image = insertWords(, "superMan", "2020-09-16");
        ImageIO.write(getBarCode("superMan"), "jpg", new File("./superMan.png"));
    }

    public static String getBase64(String tom) throws Exception {
        BufferedImage image = getBarCode("tom");
        byte[] pngs = imageToBytes(image, "PNG");
        return "data:image/png;base64,"+Base64.encodeBase64String(pngs);
    }

    public static byte[] imageToBytes(BufferedImage bImage, String format) throws Exception{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bImage,format,out);
        return out.toByteArray();
    }
}
